package com.corechina.apex_osswords.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.corechina.apex_osswords.domain.dao.SysUserGroupsMapper;
import com.corechina.apex_osswords.domain.dao.SysUserGroupsMenuMapper;
import com.corechina.apex_osswords.domain.dto.SysUserGroupsDto;
import com.corechina.apex_osswords.domain.entity.SysUserGroups;
import com.corechina.apex_osswords.domain.vo.SysUserGroupsVo;
import com.corechina.apex_osswords.service.ISysUserGroupsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户分组表 服务实现类
 * </p>
 *
 * @author cc
 * @since 2022-03-03
 */
@Service
public class SysUserGroupsServiceImpl extends ServiceImpl<SysUserGroupsMapper, SysUserGroups> implements ISysUserGroupsService {

    @Autowired
    private SysUserGroupsMapper sysUserGroupsMapper;

    @Autowired
    private SysUserGroupsMenuMapper sysUserGroupsMenuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addOrUpdate(SysUserGroupsDto sysUserGroupsDto) {
        SysUserGroups sysUserGroups = new SysUserGroups();
        BeanUtils.copyProperties(sysUserGroupsDto, sysUserGroups);
        if (sysUserGroups.getId() != null) {
            sysUserGroupsMapper.updateById(sysUserGroups);
        } else {
            sysUserGroupsMapper.insert(sysUserGroups);
        }
        sysUserGroupsMenuMapper.deleteByGroupId(sysUserGroups.getId());
        //保存用户组与菜单关系
        if (sysUserGroupsDto.getMenuIdList().size() > 0) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("groupId", sysUserGroups.getId());
            map.put("menuIdList", sysUserGroupsDto.getMenuIdList());
            sysUserGroupsMenuMapper.insertByList(map);
        }
        return sysUserGroups.getId();

    }

    @Override
    public Integer del(Integer id) {
        sysUserGroupsMenuMapper.deleteByGroupId(id);
        return sysUserGroupsMapper.deleteById(id);
    }

    @Override
    public List<SysUserGroups> getList() {
        return sysUserGroupsMapper.getList();
    }

    @Override
    public SysUserGroupsVo getOne(Integer id) {
        SysUserGroupsVo sysUserGroupsVo = sysUserGroupsMapper.getOne(id);
        sysUserGroupsVo.setMenuIdList(sysUserGroupsMenuMapper.getMenuIdByGroupId(id));
        return sysUserGroupsVo;
    }

}
